package fun.coding.leetcode;

public class StringToInteger {

	public static void main(String[] args) {
		StringToInteger ins = new StringToInteger();
		System.out.println(ins.atoi("+1"));
		System.out.println(ins.atoi("00123"));
		System.out.println(ins.atoi("-00123"));
		System.out.println(ins.atoi("   123"));
		System.out.println(ins.atoi("   "));
		System.out.println(ins.atoi("-123"));
		System.out.println(ins.atoi("  -0012a42")); // this is stupid.. should talk to interviewer to confirm those strange cases
	}
	
	/**
	 * 0, -123, 123, 00123, -00123, -, 123.5, -0, overflow, 123abc, +1, +, Integer.MAX_VALUE, Integer.MIN_VALUE
	 */
	public int atoi(String str) {
		if (str == null) return 0;
		
		str = str.trim();
		if (str.length() == 0) return 0;
		
		int n = str.length();
		
		if (n == 1 && (str.equals("-") || str.equals("+"))) return 0;
		
		boolean isSigned = false;
		
		if (str.charAt(0) == '+' || str.charAt(0) == '-') {
			isSigned = true;
		}
		
		int negativeSign = str.charAt(0) == '-' ? -1 : 1;
		
		int i = isSigned ? 1 : 0;
		
		long res = 0;
		while (i < n) {
			char c = str.charAt(i);
			if (!isValidDigit(c)) return (int)res * negativeSign;
			
			res = 10 * res + (c - '0');
			if (res*negativeSign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
			if (res*negativeSign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
			i++;
		}
		
		return (int)res * negativeSign;
	}
	
	private boolean isValidDigit(char c) {
		return c >= '0' && c <= '9';
	}

}
